<template>
  <div class="user">
    <!-- 头部 -->
    <a-form
      ref="formRef"
      style="padding-top: 20px"
      class="main-bg-color"
      :model="searchForm"
      :hideRequiredMark="true"
      :label-col="labelCol"
    >
      <a-row :gutter="20">
        <a-col :span="5" :lg="5" :xs="10">
          <a-form-item name="title" label="消息标题">
            <a-input v-model:value="searchForm.title" placeholder="请输入消息标题"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="5" :lg="5" :xs="12">
          <a-form-item name="publishId" label="发布人员">
            <a-input v-model:value="searchForm.publishId" placeholder="请输入发布人员ID"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8" :lg="8" :xs="12">
          <a-form-item label="发布时间">
            <a-range-picker v-model:value="time" @change="panelChange"></a-range-picker>
          </a-form-item>
        </a-col>
        <a-col :span="2" :offset="2">
          <a-button type="primary" @click="search" class="d-a-center">搜索</a-button>
        </a-col>
      </a-row>
    </a-form>

    <a-row justify="end" style="padding: 20px 0px">
      <a-col :span="5" :offset="1">
        <a-button type="primary" @click="send" v-has="{ a: $route, b: 2 }" class="d-a-center">发布消息</a-button>
      </a-col>
    </a-row>
    <!-- 列表 -->
    <a-table
      :columns="columns"
      :data-source="list"
      bordered
      :loading="loading"
      :pagination="pagination"
      @change="handleTableChange"
      :row-selection="rowSelection"
    >
      <template #status="{ record, index }">
        <a-switch v-model:checked="record.status" :checkedValue="1" :unCheckedValue="0" @change="changeStatus(record.status, index)" />
      </template>
      <template #operation="{ record }">
        <a-button type="link" @click="look(record.key)" v-has="{ a: $route, b: 1 }" class="d-a-center"> 查看</a-button>
        <a-button type="link" danger @click="del(record.key, true)" v-has="{ a: $route, b: 2 }" class="d-a-center">删除</a-button>
      </template>
    </a-table>
    <a-divider></a-divider>
    <a-row>
      <a-col :span="2">
        <a-button type="danger" v-has="{ a: $route, b: 2 }" @click="deleteList" class="d-a-center">删除</a-button>
      </a-col>
    </a-row>

    <!-- 发送短信 -->
    <a-modal :destroyOnClose="true" v-model:visible="visible" :title="title" :footer="null" @cancle="cancle">
      <a-form ref="editRef" :model="editForm" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-item label="消息标题" name="title">
          <a-input placeholder="请输入消息标题" v-model:value="editForm.title"></a-input>
        </a-form-item>
        <a-form-item label="消息内容" name="content">
          <a-textarea style="height: 200px" v-model:value="editForm.content"></a-textarea>
        </a-form-item>
        <a-form-item label="用户" name="type" @change="changeType">
          <a-radio-group v-model:value="editForm.type" name="type">
            <a-radio :value="0">所有用户</a-radio>
            <a-radio :value="2">用户端</a-radio>
            <a-radio :value="1">护士端</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="状态" v-if="plainOptions.length">
          <a-checkbox-group v-model:value="editForm.certificationStatus" name="checkboxgroup" :options="plainOptions">
            <template #label="{ label }">
              <span>{{ label }}</span>
            </template>
          </a-checkbox-group>
        </a-form-item>
      </a-form>
      <a-row>
        <a-col :span="4" :offset="8" v-if="title == '发布消息'">
          <a-button type="primary" @click="save" class="d-a-center">保存</a-button>
        </a-col>
        <a-col :span="4" :offset="title == '查看消息' ? 10 : 2">
          <a-button type="info" @click="cancle" class="d-a-center">关闭</a-button>
        </a-col>
      </a-row>
    </a-modal>
  </div>
</template>
<script>
import { reactive, ref, watch, computed, defineComponent, createVNode, toRefs } from 'vue'
import { CheckOutlined, EditOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { message, Modal } from 'ant-design-vue'
import { useRoute, useRouter } from 'vue-router'
import { selectAllMsg, selectOneMsg, sendMsg, deleteMsg } from '@/api/setting/index'
import { useStore } from 'vuex'
import { useModal } from '@/hooks'
export default {
  components: {
    CheckOutlined,
    EditOutlined,
    ExclamationCircleOutlined
  },
  setup() {
    const store = useStore()
    console.log(store.state.userId, '用户ID是------------')
    const router = useRouter()
    const route = useRoute()
    const formRef = ref('')
    const form = reactive({})
    // 表单验证
    const rules1 = {}
    const data = reactive({
      searchForm: {}, //发布者ID
      time: [],
      list: [],
      editForm: {},
      plainOptions: []
    })

    const userOptions = [
      {
        label: '已实名',
        value: '0'
      }
    ]
    const nurseOptions = [
      {
        label: '已实名',
        value: '0'
      },
      {
        label: '已认证',
        value: '1'
      }
    ]
    const editRef = ref('')
    const title = ref('发布消息')

    const visible = ref(false)
    const rules = {
      title: [{ required: true, message: '请输入消息标题!', trigger: 'blur' }],
      content: [{ required: true, message: '请输入短信内容!', trigger: 'blur' }]
    }

    const loading = ref(true) //表格的加载

    // 分页器
    const page = reactive({
      current: 1,
      pageSize: 10,
      total: 0
    })
    // 查询
    const search = () => {
      console.log(form, '表单内容')
      page.current = 1
      init()
    }
    // 选择时间
    const panelChange = (date, dateString) => {
      data.searchForm.createdAt = dateString[0]
      data.searchForm.endTime = dateString[1]
    }

    const columns = [
      {
        title: '编号',
        dataIndex: 'id',
        className: 'table',
        align: 'center'
      },
      {
        title: '消息标题',
        dataIndex: 'title',
        className: 'table',
        align: 'center',
        sort: true
      },
      {
        title: '发布时间',
        dataIndex: 'createdAt',
        className: 'table',
        align: 'center'
      },
      {
        title: '发布人员',
        dataIndex: 'realName',
        className: 'table',
        align: 'center'
      },
      {
        title: '操作',
        dataIndex: 'operation',
        className: 'table',
        align: 'center',
        fixed: 'right',
        slots: {
          customRender: 'operation'
        }
      }
    ]

    // 分页器
    const pagination = computed(() => ({
      current: page.current,
      pageSize: page.pageSize,
      pageSizeOptions: ['10', '20', '30'],
      showTotal: (total, range) => {
        return '共' + total + '条'
      },
      total: page.total,
      showQuickJumper: true,
      showSizeChanger: true
    }))

    // 分页器改变的时候
    const handleTableChange = (pagination, filters, sorter) => {
      console.log(pagination, '当前分页')
      page.current = pagination.current
      page.pageSize = pagination.pageSize

      // 请求列表接口
      init()
    }

    // 全选反选
    const rowSelection = ref({
      checkStrictly: false,
      onChange: (selectedRowKeys, selectedRows) => {
        console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows)
        delListId.value = selectedRowKeys
      },
      onSelect: (record, selected, selectedRows) => {
        // console.log(record, selected, selectedRows,'选择多项');
      },
      onSelectAll: (selected, selectedRows, changeRows) => {
        // console.log(selected, selectedRows, changeRows,'全选操作');
      }
    })
    const delListId = ref([]) //删除数组ID集合
    // 发送短信
    const send = () => {
      title.value = '发布消息'
      visible.value = true
    }
    const cancle = () => {
      visible.value = false
      editForm = {}
    }

    // 查看
    const look = key => {
      title.value = '查看消息'
      initDetail(key)

      visible.value = true
    }
    const save = () => {
      data.editForm.publishId = store.state.userId
      editRef.value.validate().then(async () => {
        if (!data.editForm.type) {
          message.error('请选择发送对象')
          return
        }
        let res = await sendMsg(data.editForm)
        if (res.success) {
          visible.value = false
          message.success('已成功发送')
        }
      })
    }

    const changeType = e => {
      console.log(data.editForm.type)
      data.editForm.certificationStatus = []

      switch (data.editForm.type) {
        case 1:
          console.log('11232')
          data.plainOptions = nurseOptions
          break
        case 2:
          data.plainOptions = userOptions
          break
        default:
          data.plainOptions = []
          break
      }
    }
    // 处理
    const del = (key, flag) => {
      let data = []
      if (flag) {
        data = [key]
      } else {
        data = key
      }
      const { closeModal } = useModal.confirm({
        title: '确定删除当前系统通知吗?',
        icon: createVNode(ExclamationCircleOutlined),
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk: async () => {
          let res = await deleteMsg(data)
          if (res.success) {
            message.success('删除成功')
            init()
            closeModal()
          }
        }
      })
    }
    const deleteList = () => {
      console.log(delListId.value)
      if (delListId.value.length == 0) {
        message.warning('请选择你要删除的系统通知')
        return
      }
      del(delListId.value)
    }
    init()
    async function init() {
      loading.value = true
      let obj = {
        pageNum: page.current,
        pageSize: page.pageSize,
        ...data.searchForm
      }
      let res = await selectAllMsg(obj)
      if (res.success) {
        res.object.list.map(el => (el.key = el.id))
        data.list = res.object.list
        page.total = res.object.total
        loading.value = false
      }
    }
    async function initDetail(id) {
      let res = await selectOneMsg(id)
      if (res.success) {
        data.editForm = res.object
      }
    }
    return {
      ...toRefs(data),
      formRef,
      form,
      rules,
      rules1,
      columns,
      loading,
      pagination,
      handleTableChange,
      search,
      panelChange,
      del,
      look,
      rowSelection,
      labelCol: { style: { fontWeight: 'bolder', width: '100px' } },
      send,
      visible,
      editRef,
      title,
      cancle,
      save,
      deleteList,
      changeType
    }
  }
}
</script>
<style scoped lang="less"></style>
